package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    // 注入读取了配置文件的类 获取相关的参数
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 微信用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO loginByOpenId(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO = new UserLoginVO();

        // 通过HttpClient 向微信服务发送请求 验证当前登录的用户是否合法 如果合法返回openid
        String openId = getOpenIdByCode(userLoginDTO.getCode());
        // 判断openid是否为空 如果为空 抛出异常 表示无效
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 将openId封装至 VO对象
        userLoginVO.setOpenid(openId);

        // 根据openId查询 判断当前用户是首次登录还是已经登录过
        User user = userMapper.selectByOpenId(openId);
        if (user == null) {
            // 当前用户是首次登录 先注册 再进行返回 生成令牌
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(user);
        }

        // 当前用户已经登录过 无需注册 直接返回 生成令牌即可
        // 将插入的主键封装至 VO 对象
        userLoginVO.setId(user.getId());

        // 封装Jwt令牌有效载荷 生成令牌
        Map<String, Object> payLoad = new HashMap<>();
        payLoad.put(JwtClaimsConstant.USER_ID, user.getId());
        // 生成jwt令牌
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), payLoad);

        // 将令牌 token 封装至 VO 对象
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }

    /**
     * 通过httpClient 向微信小程序后台服务发送请求 查看当前用户登录的code是否合法
     *
     * @param code
     * @return
     */
    private String getOpenIdByCode(String code) {
        // 将发送请求所需参数 封装至map集合中
        Map<String, String> map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        // 调用httpClient工具类获得 openid
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);

        // 通过fastjson解析 json数据
        return JSON.parseObject(json).getString("openid");
    }
}
